from urllib import request, parse
import re
import requests
import json
import http.cookiejar

# 仅出于学习目的编写，！！代码只有参考价值！！，无法真正做到自动化（比如网站修改提交表单格式就有可能gg）
# 使用程序出问题的概不负责~，！！代码只有参考价值！！
# 每天准时打卡才是好同志

#  账户密码填入
username = ""
password = ""

typeToken = None
typeCookies = None

accessUrl = ""

realToken = ""

baseInfo = None

sendInfo = None


def getTypeToken():
    global typeToken
    global typeCookies
    url = 'https://cas.dgut.edu.cn/home/Oauth/getToken/appid/illnessProtectionHome/state/home.html'

    typeCookies = http.cookiejar.CookieJar()
    handler = request.HTTPCookieProcessor(typeCookies)
    opener = request.build_opener(handler)
    myResponse = opener.open(url)
    html = myResponse.read().decode('utf-8')
    typeToken = re.findall(r'var token = "(.+?)";', html)[0]
    print("获得typeToken")


def getAccessToken():
    global typeToken
    global typeCookies
    global accessUrl
    url = "https://cas.dgut.edu.cn/home/Oauth/getToken/appid/illnessProtectionHome/state/home.html"

    payload = {
        'username': username,
        'password': password,
        '__token__': typeToken
    }

    payload = parse.urlencode(payload).encode(encoding='UTF8')
    handler = request.HTTPCookieProcessor(typeCookies)
    opener = request.build_opener(handler)
    myResponse = opener.open(url, data=payload)

    myResponse = myResponse.read().decode('utf-8').replace("\\", "")
    accessUrl = re.findall(r'"info":"(.+?)"}', myResponse)[0]
    print("获得第一个url")


def visitAccessUrlAndGetRealToken():
    global accessUrl
    global realToken
    myRequest = request.Request(url=accessUrl)
    myResponse = request.urlopen(myRequest)
    realToken = re.findall(r'access_token=(.+?)$', myResponse.url)[0]
    print("获得realToken")


def getBaseInfo():
    global realToken
    global baseInfo
    url = "https://yqfk.dgut.edu.cn/home/base_info/getBaseInfo"
    header = {
        "authorization": "Bearer" + " " + realToken
    }
    myRequest = request.Request(url=url, headers=header)
    myResponse = request.urlopen(myRequest)
    baseInfo = json.loads(myResponse.read())
    print("获得baseInfo")


def makeSendInfo():
    global sendInfo
    global baseInfo

    sendInfo = baseInfo.get("info").copy()

    removeAttr = [
        "id",
        "username",
        "name",
        "class_name",
        "faculty_id",
        "faculty_name",
        "jihuan",
        "huji",
        "family_address",
        "current_area",
        "have_take_bus",
        "family_is_specific_people",
        "have_gone_hubei",
        "create_time",
        "current_country",
        "current_province",
        "current_city",
        "connect_card_type",
        "connect_card_number",
        "huji_district",
        "jiguan_district",
        "family_district",
        "connect_person_2",
        "connect_card_type_2",
        "connect_card_number_2",
        "connect_tel_2",
        "continue_days",
        "can_submit",
        "whitelist",
        "msg",
        "importantAreaMsg",
        "class_id"
    ]

    for i in removeAttr:
        try:
            sendInfo.pop(i)
        except KeyError as e:
            pass
        finally:
            pass

    print("构建发送请求体")


def finalSend():
    global sendInfo
    header = {
        "authorization": "Bearer" + " " + realToken,
        'Content-Type': 'application/json; charset=utf-8'
    }
    url = "https://yqfk.dgut.edu.cn/home/base_info/addBaseInfo"
    print("发送请求")
    myResponse = requests.post(url=url, headers=header, data=json.dumps(sendInfo))
    myResponse = myResponse.json()
    print("请求响应："+myResponse.get("message"))

    


if __name__ == '__main__':
    getTypeToken()
    getAccessToken()
    visitAccessUrlAndGetRealToken()
    getBaseInfo()
    makeSendInfo()
    finalSend()
